package top.zsyle.sycc.consumer;

import com.alibaba.fastjson.JSONObject;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import top.zsyle.sycc.domain.MediaFile;
import top.zsyle.sycc.service.IMediaFileService;
import java.nio.charset.StandardCharsets;

@Component
@RocketMQMessageListener(
        consumerGroup = "service-media-producer",
        topic = "media-topic",
        selectorExpression = "push:tag",
        //消息模式：默认集群模式，只有一个消费者能够消费消息
        //广播模式：只要订阅了相同topic的消费者都能消费消息
        messageModel = MessageModel.CLUSTERING
)
public class MediaConsumer implements RocketMQListener<MessageExt> {

    /**
     * ACK机制：当方法没有返回值时，如果没有抛出异常则证明消费成功
     * 抛出异常则消费失败，重新消费消息 默认16次
     */

    @Autowired
    private IMediaFileService mediaFileService;

    @Override
    public void onMessage(MessageExt messageExt) {
        byte[] body = messageExt.getBody();
        String str = new String(body, StandardCharsets.UTF_8);
        MediaFile mediaFile = JSONObject.parseObject(str, MediaFile.class);
        mediaFileService.handleFile2m3u8(mediaFile);
    }
}
